import { getApps } from '.';
import { importHTML } from './import-html';
import { getNextRoute, getPrevRoute } from './rewrite-router';

// let currentApp = {};
// export const getCurrentApp = () => currentApp;

export const handleRouter = async () => {
  // 2.匹配子应用
  console.log(getPrevRoute(), getNextRoute(), '==========');
  debugger;
  const apps = getApps();

  // 获取上一个路由应用
  const prevApp = apps.find(item => getPrevRoute().startsWith(item.activeRule));

  // 获取下一个路由应用
  const app = apps.find(item => getNextRoute().startsWith(item.activeRule));

  if (prevApp && app && prevApp.name == app.name) return;
  if (prevApp) {
    await unmount(prevApp);
  }
  if (!app) return;

  // currentApp = app;

  // 3.加载子应用
  const { template, getExternalScripts, execScripts } = await importHTML(
    app.entry
  );
  const container = document.querySelector(app.container);
  container.appendChild(template);

  // 配置全局环境变量
  window.__POWERED_BY_QIANKUN__ = true;
  window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__ = app.entry + '/';

  const appExports = await execScripts();

  app.bootstrap = appExports.bootstrap;
  app.mount = appExports.mount;
  app.unmount = appExports.unmount;
  await bootstrap(app);
  await mount(app);

  // 请求获取子应用的资源： HTML、CSS、JS
  // const html = await fetch(app.entry).then(res => res.text());
  // console.log(html, '==========');
  // const container = document.querySelector(app.container);
  // // 1. 客户端渲染需要通过执行javaScript来生成内容
  // // 2. 浏览器处于安全考虑，innerHTML 中的script不会加载执行
  // container.innerHTML = html;

  // 4.渲染子应用
};

async function bootstrap(app) {
  app.bootstrap && (await app.bootstrap());
}
async function mount(app) {
  app.mount &&
    (await app.mount({
      container: document.querySelector(app.container)
    }));
}
async function unmount(app) {
  app.unmount &&
    (await app.unmount({
      container: document.querySelector(app.container)
    }));
}
